# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '20181121114441': {  # dwc 支付宝2.7%（10---5000）
        'API_KEY': '32d8f7e8129b49a5b4b38fbd3067dfbb',
        'gateway': 'http://47.107.229.155/api/pay',
        'query_gateway': 'http://47.107.229.155/api/order/get/{}/{}',
    },
    '20181210151249': {  # zs 支付宝2.7%（10---5000）
        'API_KEY': 'e67a7fa569154012b22f4f757a55409d',
        'gateway': 'http://47.107.229.155/api/pay',
        'query_gateway': 'http://47.107.229.155/api/order/get/{}/{}',
    },
    '20181210151408': {  # witch 支付宝2.7%（10---5000）
        'API_KEY': '99471dde5d36492395d62d6cb26bf351',
        'gateway': 'http://47.107.229.155/api/pay',
        'query_gateway': 'http://47.107.229.155/api/order/get/{}/{}',
    },
    '20181210151349': {  # loki 支付宝2.7%（10---5000）
        'API_KEY': '3968bf8b9629484096b5b2e56fd9b96d',
        'gateway': 'http://47.107.229.155/api/pay',
        'query_gateway': 'http://47.107.229.155/api/order/get/{}/{}',
    },
    '20190527160627': {  # dwc 微信扫码3.5%（50---5000)
        'API_KEY': 'b3db48b326434dc797f6055b6ecc8bd6',
        'gateway': 'http://47.107.229.155/api/pay',
        'query_gateway': 'http://47.107.229.155/api/order/get/{}/{}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s += str(key)
    _LOGGER.info('xintaipay sign str : %s', s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("xintaipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_pay_type(service):
    if service == 'alipay':
        return '1'
    elif service == 'qr_wechat':
        return '2'
    return '1'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('appUserId', str(pay.user_id)),
        ('clientIp', _get_device_ip(info)),
        ('outTradeNo', str(pay.id)),
        ('signType', 'MD5'),
        ('transType', _get_pay_type(service)),
        ('merId', app_id),
        ('body', 'charge'),
        ('totalFee', str(int(pay_amount))),
        ('notifyUrl', '{}/pay/api/{}/xintaipay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('timeStamp', local_now().strftime('%Y-%m-%d %H:%M:%S')),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    data = json.dumps(parameter_dict)
    _LOGGER.info("xintaipay create: %s", data)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_get_gateway(app_id), data=data, headers=headers, timeout=5, verify=False)
    _LOGGER.info("xintaipay create rsp : %s", response.text)
    return {'charge_info': json.loads(response.text)['obj']['payInfo']}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = json.loads(request.body)
    _LOGGER.info("xintaipay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['outTradeNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('xintaipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = 'success'
    trade_no = data['orderNo']
    total_fee = float(data['totalFee'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 'success' and total_fee > 0.0:
        _LOGGER.info('xintaipay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    merId = app_id
    outTradeNo = str(pay_order.id)
    url = _get_query_gateway(app_id).format(merId, outTradeNo)
    response = requests.get(url)
    _LOGGER.info('xintaipay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['obj']['status'])
        total_fee = float(data['obj']['totalFee'])
        trade_no = data['obj']['orderNo']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == '1':
            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('xintaipay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
